package com.gzc.just.play.last.war.loginserver.handler;

import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;
import com.gzc.just.play.last.war.loginserver.service.AuthService;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 登出消息处理器
 * 处理用户登出请求
 */
@Component
public class LogoutMessageHandler implements SimpleMessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(LogoutMessageHandler.class);
    
    @Autowired
    private AuthService authService;
    
    private static final int LOGOUT = 4002;
    
    @Override
    public void handle(Object message, ChannelHandlerContext ctx) throws Exception {
        // 从上下文中获取用户ID
        io.netty.util.AttributeKey<Long> userIdKey = io.netty.util.AttributeKey.valueOf("userId");
        Long userId = ctx.channel().attr(userIdKey).get();
        
        if (userId == null) {
            logger.warn("Logout request from unauthenticated connection");
            sendLogoutResponse(ctx, false, "Not logged in");
            return;
        }
        
        // 执行登出操作
        boolean success = authService.logout(userId);
        
        // 发送登出响应
        if (success) {
            sendLogoutResponse(ctx, true, "Logout successful");
            logger.info("User {} logged out successfully", userId);
        } else {
            sendLogoutResponse(ctx, false, "Logout failed");
            logger.warn("Logout failed for user: {}", userId);
        }
        
        // 清除上下文中的用户ID
        ctx.channel().attr(userIdKey).set(null);
    }
    
    private void sendLogoutResponse(ChannelHandlerContext ctx, boolean success, String message) {
        // 实际实现中应该构造并发送登出响应消息
        logger.info("Sending logout response: success={}, message={}", success, message);
    }

    @Override
    public int getMessageId() {
        return LOGOUT;
    }
    
    @Override
    public String getName() {
        return "LogoutMessageHandler";
    }
    
    @Override
    public Logger getLogger() {
        return logger;
    }
}